<?php
namespace app\admin\controller;
use think\Session;
use app\admin\model\Admin as AdminModel;
class Admin extends Base
{
	//后台首页
	public function index()
	{
		return $this->fetch();
	}

	//登录后台
    public function login()
    {
    	if($this->request->isPost()){
    		$post = $this->request->post();
    		if(empty($post['username']) || empty($post['password'])){
    			$this->error('用户名或密码不能为空');
    		}
    		$password = md5($post['password'].'YiHeGeGe');
    		$admin = new AdminModel;
    		$result = $admin->where(['username'=>$post['username'],'password'=>$password])->find();
    		if(!$result){
    			$this->error('用户名或密码错误','login');
    		}
    		Session::set('admin',$result->toArray());
    		$this->redirect('admin/index');
    	}else{
    		if(Session::has('admin')){
    			$this->redirect('admin/index');
    		}
    		return $this->fetch();
    	}
    }

    //退出登录
    public function logout()
    {
    	Session::delete('admin');
    	$this->redirect('admin/login');
    }

    //添加管理员
    public function create()
    {
    	if($this->request->isPost()){
    		$post = $this->request->post();
    		if(empty($post['username']) || empty($post['password']) || empty($post['password2'])){
    			$this->error('用户名或密码不能为空');
    		}
    		if($post['password'] !== $post['password2']){
    			$this->error('密码确认密码不一致');
    		}
    		$post['password'] = md5($post['password'].'YiHeGeGe');
    		$admin = new AdminModel;
    		$admin->data($post);
    		$admin->allowField(true)->save();
    		if(!$admin->id){
    			$this->error('添加管理员失败');
    		}
    		$this->success('添加管理员成功');
    	}else{
    		return $this->fetch();
    	}
    }

    //管理员列表
    public function list()
    {
    	$admin = new AdminModel;
    	$list = $admin->order('id desc')->paginate(10);
    	$this->assign('list', $list);
    	return $this->fetch();
    }

    //删除管理员
    public function delete($id)
    {
        if(!AdminModel::destroy($id)){
            $this->error('删除管理员失败');
        }
        $this->success('删除管理员成功');
    }
}